import React, { Component } from 'react'
import '../assets/css/shopcartList.scss'

export default class ShopcartList extends Component {
  constructor() {
    super()
    //定义状态数据
    this.state = {
      shopcartList: [
        {
          pid: '1001',
          pname: '欧莱雅男士护肤',
          price: 38,
          num: 1
        },
        {
          pid: '1002',
          pname: 'OLAY女士防皱润肤露',
          price: 108,
          num: 1
        },
        {
          pid: '1003',
          pname: '自然堂女士护肤',
          price: 108,
          num: 2
        },
        {
          pid: '1004',
          pname: '兰蔻香水',
          price: 1038,
          num: 1
        },
        {
          pid: '1005',
          pname: '大宝SOD,每个人选择',
          price: 8,
          num: 1
        }
      ]
    }
  }

  //改变数量的方法
  changeNum = (sign, index) => {
    switch (sign) {
      case '+':
        //如下这个操作，它只能将数据进行更新，页面没有进行变化
        this.state.shopcartList[index].num++
        break
      case '-':
        if (this.state.shopcartList[index].num > 1) {
          this.state.shopcartList[index].num--
        } else {
          window.alert('数量不能少于0')
        }
        break
    }
    this.setState({
      shopcartList: this.state.shopcartList
    })
  }
  //计算总价的函数
  total = ary => `￥${ary.reduce((pre, cur) => pre + cur.price * cur.num, 0).toFixed(2)}`
  //删除方法
  deleteShopcartList = index => {
    if (window.confirm('您确定要删除吗?')) {
      //数组中的splice方法的参数的含义
      //第一参数：表示要操作数组的下标
      //第二个参数:表示的是要删除几个数据
      this.state.shopcartList.splice(index, 1)
      //使用this.setState来页面
      this.setState({
        shopcartList: this.state.shopcartList
      })
    }
  }
  render() {
    const { shopcartList } = this.state
    return (
      <div>
        <h2>购物车</h2>
        <table>
          <thead>
            <tr>
              <td>序号</td>
              <td>名称</td>
              <td>价格</td>
              <td>数量</td>
              <td>小计</td>
              <td>操作</td>
            </tr>
          </thead>
          <tbody>
            {
              shopcartList.map((item, index) => <tr key={item.pid}>
                <td>{item.pid}</td>
                <td>{item.pname}</td>
                <td>{item.price}</td>
                <td>
                  <button className='operbtn' onClick={() => { this.changeNum('-', index) }}>-</button>
                  {item.num}
                  <button className='operbtn' onClick={() => { this.changeNum('+', index) }}>+</button>
                </td>
                <td>{item.price * item.num}</td>
                <td>
                  <button className='delBtn' onClick={() => { this.deleteShopcartList(index) }}>删除</button>
                </td>
              </tr>)
            }
          </tbody>
          <tfoot>
            <tr>
              <td colSpan={6}>
                {this.total(shopcartList)}
              </td>
            </tr>
          </tfoot>
        </table>
      </div>
    )
  }
}
